package com.hcl.orm.core.spring;

import com.hcl.orm.core.dialect.handler.AbstractDialectHandler;
import com.hcl.orm.core.dialect.handler.SqlDialectHandlerFactory;
import com.hcl.orm.core.executor.DataSourceTypeLookup;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcOperations;

import java.util.HashMap;
import java.util.Map;

/**
 * @author hucl
 * @projectName jim-orm
 * @description: TODO
 * @date 2021/5/1216:49
 */
public class MultiDialectDaoFactoryBean<T> implements FactoryBean<T>, InitializingBean {
    private Class<T> daoInterface;
    @Autowired
    private JdbcOperations jdbcOperations;
    @Autowired
    private SqlDialectHandlerFactory sqlDialectHandlerFactory;
    @Autowired
    private DataSourceTypeLookup dataSourceTypeLookup;
    /**
     * 代理工程缓存
     */
    private final Map<Class<?>, MultiDialectDaoProxyFactory<?>> cachedProxyFactory = new HashMap<Class<?>, MultiDialectDaoProxyFactory<?>>();
    private BeanFactory beanFactory;

    @Override
    public T getObject() throws Exception {
        MultiDialectDaoProxyFactory<T> daoProxyFactory = (MultiDialectDaoProxyFactory<T>) cachedProxyFactory.get(daoInterface);
        if (daoProxyFactory == null) {
            daoProxyFactory = new MultiDialectDaoProxyFactory<T>(daoInterface);
            cachedProxyFactory.put(daoInterface, daoProxyFactory);
        }

        return daoProxyFactory.newInstance(jdbcOperations);
    }

    @Override
    public Class<?> getObjectType() {
        return this.daoInterface;
    }

    public void setDaoInterface(Class<T> daoInterface) {
        this.daoInterface = daoInterface;
    }

    public void setJdbcOperations(JdbcOperations jdbcOperations) {
        this.jdbcOperations = jdbcOperations;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        AbstractDialectHandler dialectHandler = sqlDialectHandlerFactory.createDialectHandler(dataSourceTypeLookup,
                daoInterface.getPackage().toString());
        DaoMethodCacheManager.refresh(dialectHandler,daoInterface.getMethods());
    }
}
